<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :minHeight="20"
    :width="800"
    okText="提交"
    @register="register"
    :title="modalTitle"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #slotVariable="{ model, field }">
          <checkTag
            :value="model[field]"
            :isErroByVariable="isErroByVariable"
            @checkTag="handleCheckTag"
          />
        </template>
        <template #menu="{ model, field }">
          <BasicTree
            class = "attrTree"
            v-model:value="model[field]"
            :treeData="treeData"
            :fieldNames="{ title: 'Name', key: 'Key' }"
            checkable
            toolbar
            title="添加属性"
          />
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { computed, nextTick, ref, unref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { getMenuList } from '/@/views/project/system/role/role.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { checkName } from '/@/utils/index';
  import checkTag from '/@/components/selectTag/index.vue';
  import { getPopupContainer } from '/@/utils';
  import { getdatalist,gettags } from '/@/api/alertRules';
  import { BasicTree, TreeItem } from '/@/components/Tree';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });
  let isErroByVariable = ref<boolean>(false);
  const treeData = ref<TreeItem[]>([]);
  let modalTitle = computed(() => {
    return `${props.info.type === 'add' ? '新增' : '编辑'}告警`;
  });
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'Name',
      component: 'Input',
      label: '名称：',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkName(value, `名称`),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'TagFullName',
      component: 'Input',
      label: '变量：',
      slot: 'slotVariable',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请选择变量',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'AlarmTypeCode',
      component: 'Select',
      label: '报警类别：',
      colProps: {
        span: 24,
      },
      componentProps: {
        getPopupContainer: () => getPopupContainer(),
        options: [],
        fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
      },
      rules: [
        {
          required: true,
          message: '请选择报警类别',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Description',
      component: 'InputTextArea',
      label: '描述：',
      colProps: {
        span: 24,
      },
    },
    {
      label: ' ',
      field: 'DiagnosisTags',
      slot: 'menu',
      component: 'Input',
      colProps: {
        span: 24,
      },
    },
  ];
  
  const [
    registerForm,
    { validateFields, resetFields, clearValidate, updateSchema, setFieldsValue },
  ] = useForm({
    labelWidth: 120,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const emit = defineEmits(['submitSuccess']);
  const [register] = useModal();

  async function handleSubmint() {
    try {
      let res = await validateFields();
      if (props.info.type === 'add') {
        // props.info.data.Key,
        await props.info.addApi([
          props.info.data.serverName,
          res.Name,
          res.TagFullName,
          res.Description,
          res.AlarmTypeCode,
          res.DiagnosisTags
        ]);
      } else {
        //
        await props.info.editApi([
          props.info.data.serverName,
          props.info.data.Name,
          res.Name,
          res.TagFullName,
          res.Description,
          res.AlarmTypeCode,
          res.DiagnosisTags
        ]);
      }

      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', {});
    } catch (error: any) {
      isErroByVariable.value = ['', null, undefined].indexOf(error.values.TagFullName) >= 0;
      console.log('not passing', error);
    }
  }
  function handleVisibleChange(visible) {
    if (visible) {
      nextTick(async () => {
        console.log( props.info.data)
        let { Description, Name, TagFullName, AlarmTypeCode,DiagnosisTags } = props.info.data;
        
        if (props.info.type === 'update') {
          setFieldsValue({ Description, Name, TagFullName,AlarmTypeCode,DiagnosisTags});
          // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
          treeData.value = (await gettags([TagFullName])) as any as TreeItem[];
        }

        clearValidate();
        await getCategory();
      });
    } else {
      isErroByVariable.value = false;
      resetFields();
    }
  }
  async function handleCheckTag(val) {
    let resList = val.val;
    let targetInfo = Array.isArray(resList) && resList.length > 0 ? resList[0] : {};
    setFieldsValue({
      TagFullName: targetInfo.FullName,
    });
    treeData.value = (await gettags([targetInfo.FullName])) as any as TreeItem[];
    isErroByVariable.value = false;
  }
  async function getCategory() {
    let res = await getdatalist([
      {
        Code: 'alarm_type',
      },
    ]);
    updateSchema({
      field: 'AlarmTypeCode',
      componentProps: {
        options: res,
      },
    });
  }
</script>

<style lang="less" scoped>
  .slot-select {
    width: 100%;
    height: 32px;
    padding: 0 11px;
    display: flex;
    position: relative;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    cursor: pointer;
  }

  .slot-select:hover {
    border: 1px solid #1e80ff;
  }

  .slot-select-con {
    margin-right: 18px;
    line-height: 30px;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #000000d9;
    font-size: 14px;
  }

  .con-placeholder {
    color: #bfbfbf;
  }

  .icon-style {
    line-height: 30px;
    font-size: 11px;

    color: #bfbfbf;
  }

  .erro-style {
    border: 1px solid #ed6f6f !important;
  }

  .slot-select-diabled {
    background: #f5f5f5;
    cursor: not-allowed;

    .slot-select-con {
      color: rgba(0, 0, 0, 0.25);
    }
  }

  .slot-select-diabled:hover {
    border: 1px solid #d9d9d9;
  }
  .attrTree{
    position: relative;
    top: -13px;
    left: -96px;

    ::v-deep(.ant-tree-list-holder-inner) {
        flex-wrap: wrap;
        flex-direction: row !important;
        padding-top: 5px;
        padding-left: 80px;
      }
    ::v-deep(.ant-tree-treenode) {
        min-width: 170px;
      }
  }
</style>
